import Router from 'koa-router'

import visitDorm from '../dbs/models/visit'

let router = new Router({ prefix: '/visit' })

// 来访登记
router.get('/visitUp', async (ctx, next) => {
  let name = ctx.query.name
  let tel = ctx.query.tel
  let matter = ctx.query.matter
  let dorm = ctx.query.dorm
  let visitedName = ctx.query.visitedName
  let tower = ctx.query.tower
  let watch = ctx.query.watch
  let remake = ctx.query.remake
  let leaveTime = ctx.query.leaveTime
  let where = {
    name,
    tel,
    matter,
    tower,
    dorm,
    visitedName,
    watch,
    remake,
    leaveTime
  }
  // console.log(where)
  const damageUp = new visitDorm(where)
  let code
  try {
    await damageUp.save()
    code = 0
  } catch (e) {
    code = -1
  }
  ctx.body = {
    msg: code === 0 ? '已上传来访人员信息' : '上传失败',
    code: code
  }
})

// 来访人员列表
router.get('/findVisiters', async (ctx, next) => {
  let tower = ctx.query.tower
  let page = Number(ctx.query.pagenum)//当前第几页
  let size = Number(ctx.query.pagesize)//每页显示的记录条数
  let where = { tower }
  // console.log(tower, page, size)
  let options = { "limit": size, "skip": (page - 1) * size }

  try {
    let result = await visitDorm.find(where, null, options)
    let count = await visitDorm.find(where, null)
    let total = count.length
    if (total !== 0) {
      ctx.body = {
        total: total,
        visitersList: result,
        meta: {
          msg: "已找到来访人员名单",
          code: 200
        }
      }
    } else {
      ctx.body = {
        total: total,
        visitersList: result,
        meta: {
          msg: "目前未有访问人员,",
          code: 200
        }
      }
    }

  } catch (error) {
    ctx.body = {
      meta: {
        msg: "错误,error",
        code: 500
      }
    }
  }
})

// 来访人员离开
router.get('/visiterLeft', async (ctx, next) => {
  // console.log(1111)
  let { _id, leaveTime } = ctx.query
  // console.log(_id, leaveTime)
  let where = {
    _id
  }
  if (!leaveTime) {
    try {
      let result = await visitDorm.updateOne(where, { leaveTime: new Date().getTime() })
      ctx.body = {
        result,
        meta: {
          code: 200,
          msg: '已添加来访人员离开时间'
        }
      }
    } catch (error) {
      ctx.body = {
        meta: {
          code: 500,
          msg: '添加来访人员离开时间失败'
        }
      }
    }
  } else {
    let result = await visitDorm.updateOne(where, { leaveTime: '' })
    try {
      ctx.body = {
        result,
        meta: {
          code: 200,
          msg: '已删除来访人员离开时间'
        }
      }
    } catch (error) {
      ctx.body = {
        meta: {
          code: 500,
          msg: '删除来访人员离开时间失败'
        }
      }
    }
  }
})

// 某年学校宿舍来访人员统计
router.get('/allVisiters', async (ctx, next) => {
  // console.log(ctx.query)
  let { Syear } = ctx.query
  let { Eyear } = ctx.query
  // console.log(Eyear)
  let where = {
    visitTime: {
      "$gte": new Date(Syear),
      "$lte": new Date(Eyear)
    }
  }
  // console.log(where)
  let result = await visitDorm.find(where)
  let n = []
  let mounth = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  result.forEach(valid => {
    // console.log(String(valid.visitTime))
    // console.log(String(valid.visitTime).slice(4, 7))
    mounth.forEach(v => {
      if (String(valid.visitTime).slice(4, 7) === v) {
        n.push(v)
      }
    })
  })
  // console.log(n)
  // 统计每个月中来访人员的个数
  let s = n.reduce((pre, next) => {
    // console.log(1111, pre, next)
    if (next in pre) {
      pre[next]++;
    } else {
      // console.log(2)
      pre[next] = 1;
    }
    return pre
  }, {})
  // console.log(s)
  // 这里用来解决其它月份为来访人员为0的时候出现的出现对应月份和来访人员数据不对等的问题
  let newS = {}
  mounth.forEach(valid => {
    // console.log('valid:', valid)
    for (let key in s) {
      // console.log('key:', key)
      // 查找数组s中来访人员为0的月份
      if (key !== valid) {
        // 防止给已有来访人员的月份重新赋值为0
        if (newS[valid]) {
          // 空操作
          next
        } else {
          newS[valid] = 0
        }
      } else {
        newS[valid] = s[key]
      }
    }
  })
  // console.log(newS)
  ctx.body = {
    option: {
      title: {
        text: Syear.slice(0, 4) + '年全校学生宿舍每月来访人员'
      },
      tooltip: {},
      legend: {
        data: ['人数']
      },
      xAxis: {
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      },
      yAxis: {},
      series: [{
        name: '每月来访人员',
        type: 'bar',
        data: Object.values(newS)
      },
      {
        name: '每月来访人员',
        type: 'line',
        color: '#2593c2',
        data: Object.values(newS)
      }]
    },
    meta: {
      code: 200,
      msg: '请求数据成功'
    }
  }
})

// 当前楼宇来访人员统计
router.get('/curTowerVisiters', async (ctx, next) => {
  // console.log(ctx.query)
  let { Syear, Eyear, tower } = ctx.query
  let where = {
    tower,
    visitTime: {
      "$gte": new Date(Syear),
      "$lte": new Date(Eyear)
    }
  }
  let result = await visitDorm.find(where)
  // 过滤数据
  let n = []
  let mounth = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  // 截取月份
  // console.log(result[0].visitTime)
  // console.log(String(result[0].visitTime))
  result.forEach(valid => {
    mounth.forEach(v => {
      // 如果访问时间的月份===mounth中对应的月份，就将该月份抽取出来添加到数组n
      if (String(valid.visitTime).slice(4, 7) === v) {
        n.push(v)
      }
    })
  })
  // 统计每个月中来访人员的个数，将相同月份的来访人数进行累加
  let s = n.reduce((pre, next) => {
    if (next in pre) {
      pre[next]++;
    } else {
      // console.log(2)
      pre[next] = 1;
    }
    return pre
  }, {})
  // 这里用来解决其它月份为来访人员为0的时候出现的出现对应月份和来访人员数据不对等的问题
  // 也就是1-12月中，如果某个月份没有来访人员，就将这个月份自动补全数据，值为0
  let newS = {}
  mounth.forEach(valid => {
    for (let key in s) {
      // 查找数组s中来访人员为0的月份
      if (key !== valid) {
        // 防止给已有来访人员的月份重新赋值为0
        if (newS[valid]) {
          next
        } else {
          newS[valid] = 0
        }
      } else {
        newS[valid] = s[key]
      }
    }
  })
  ctx.body = {
    option: {
      title: {
        text: Syear.slice(0, 4) + '年' + tower + '栋学生宿舍每月来访人员'
      },
      tooltip: {},
      legend: {
        data: ['人数']
      },
      xAxis: {
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      },
      yAxis: {},
      series: [{
        name: '每月来访人员',
        type: 'bar',
        // 将对象的值转换成数组
        data: Object.values(newS)
      },
      {
        name: '每月来访人员',
        type: 'line',
        color: '#2593c2',
        data: Object.values(newS)
      }]
    },
    meta: {
      code: 200,
      msg: '请求数据成功'
    }
  }
})
export default router
